import { Upload, GetProp, message, Modal, Spin } from 'antd';
import React from 'react';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useRequest } from 'ahooks';
import { apiInterceptors, getApplogoList, uploadAppLogo,getApplogo } from '@/client/api';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import Icon, { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import Image from 'next/image';
import { useTranslation } from 'react-i18next';
import styles from '../styles.module.css';
import { logoUrl } from '@/utils';

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error(t('uploadLimitDesc'));
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error(t('uploadSizeDesc')+'2MB!');
  }
  return isJpgOrPng && isLt2M;
};

const UpdateAvatarModal: React.FC<{
  open: boolean;
  onCancel: () => void;
  updateCurrentAppLogo?: any;
  type?: 'add' | 'edit';
  appInfo: object;
}> = ({ open, onCancel, type = 'add', updateCurrentAppLogo, appInfo }) => {

  const { t, i18n } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>(appInfo.app_logo?logoUrl+appInfo.app_logo : '/ai/'+`${appInfo?.team_context ? appInfo?.team_context?.chat_scene+'.png' : 'chat_agent.png'}`);

  const handleChange = async (info) => {
      // if (info.file.status === 'uploading') {
      //   setLoading(true);
      //   return;
      // }
      // if (info.file.status === 'done') {
      //   getBase64(info.file.originFileObj as FileType, (url) => {
      //     setLoading(false);
      //     setImageUrl(url);
      //   });
      // }
      setLoading(true);
      
      const formData = new FormData();
      formData.append('image_file',info.file)
      const [, res] = await apiInterceptors(uploadAppLogo({type:2,file:formData}));
      if(res){
        setImageUrl(logoUrl+res)
        setSelectedAvatar(res);
        setLoading(false);
      }else{
        setLoading(false);
      }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
    </div>
  );
  const [recommendedAvatars, setRecommendedAvatars] = useState([])
  const [selectedAvatar, setSelectedAvatar] = useState('');

  const handleAvatarSelect = (avatarUrl: string) => {
    setSelectedAvatar(avatarUrl.id);
  };
  const onOk = ()=>{
    updateCurrentAppLogo(selectedAvatar)
    onCancel();
  }

  // 系统推荐头像
  const initSysLogos = useCallback(async () => {
    const [_, data] = await apiInterceptors(getApplogoList(2));
    const list = data.map((item)=>{ return {url:logoUrl+item,id:item } });
    setRecommendedAvatars(list)
  },[]);

  useEffect(() => {
    initSysLogos()
  },[initSysLogos])


  return <Modal title={t('ModifyAvatar')} open={open} onOk={onOk} className={styles['extra-container']}
    onCancel={onCancel}>
      <Spin spinning={loading}>
        <div className='p-3 flex flex-col'>
          <div>{t('SystemRecommendedAvatars')}</div>
          <div className="avatar-list flex flex-wrap gap-2 mt-3 h-40 overflow-y-scroll">
            {recommendedAvatars.map((avatarUrl, index) => (
              <Image
                src={avatarUrl.url}
                alt=""
                width={75}
                height={75}
                key={index}
                className={`cursor-pointer border  ${selectedAvatar === avatarUrl.id ? 'border-[#8665FF] dark:border-[#8665FF]' : 'border-[#d5e5f6] dark:border-[#ffffff66]'}`}
                onClick={() => handleAvatarSelect(avatarUrl)}
              />
            ))}
          </div>
          <div className='flex gap-3 my-3'>
            <div>{t('CustomizeAvatar')}</div>
            <div>
              <Upload name="avatar"  listType="picture-card"
                beforeUpload={beforeUpload}
                customRequest={handleChange}
                showUploadList={false}
                maxCount={1}
                multiple={false}
                className='avatar-uploader'
                accept='.png,.jpeg'
              >
                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width:75,height:75 }} /> : uploadButton}
              </Upload>
              <div className='mt-3'>{t('UploadDesc')}</div>
            </div>
          </div>
        </div>
      </Spin>
  </Modal>
}
export default UpdateAvatarModal;